package com.jiuxian.scheduling.config.server;

import com.jiuxian.scheduling.config.ConfigServer;
import com.jiuxian.scheduling.listener.zk.ZkDataListener;
import com.jiuxian.scheduling.util.ZKClientUtil;
import com.jiuxian.scheduling.vo.SchedingVO;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by wangjingqing on 2017/11/9.
 */
public class ZKConfigServer implements ConfigServer {

    Logger logger = LoggerFactory.getLogger(ZKConfigServer.class);
    @Override
    public String add(SchedingVO schedingVO) {
        try {
            ZKClientUtil.creatNode(schedingVO.getName(),schedingVO);
        } catch (Exception e) {
            logger.error("创建节点失败{}",schedingVO.toString());
            return null;
        }
        return schedingVO.getName();
    }

    @Override
    public Boolean update(SchedingVO schedingVO) {
        return ZKClientUtil.setDate(schedingVO.getName(),schedingVO);
    }

    @Override
    public Boolean exist(String name) {
        return ZKClientUtil.exists(name);
    }

    @Override
    public SchedingVO get(String name) {
        return (SchedingVO)ZKClientUtil.getData(name);
    }

    @Override
    public Boolean delete(String name) {
        return ZKClientUtil.delNode(name);
    }

    @Override
    public List<SchedingVO> getAll() {
        List<SchedingVO> schedingVOS = new ArrayList<>();
        List<String> names = ZKClientUtil.getNodes();
        if(CollectionUtils.isNotEmpty(names)){
            names.forEach(name->schedingVOS.add(get(name)));
        }
        return schedingVOS;
    }

    @Override
    public void addNodeListener(List<String> names) {
        if(CollectionUtils.isNotEmpty(names)){
            names.forEach(info->ZKClientUtil.addDataListener(info,new ZkDataListener()));
        }
    }
}
